package leetcode_1_200;

import node.ListNode;

import java.util.ArrayList;
import java.util.List;

public class LeeCode_25 {
    public static void main(String[] args) {
//        System.out.println(reverseKGroup(new ListNode(1, new ListNode(2, new ListNode(3,
//                new ListNode(4, new ListNode(5))))), 3));
        System.out.println(reverseKGroup(new ListNode(1, new ListNode(2)), 2));
    }
    private static ListNode reverseKGroup(ListNode head, int k) {
        List<ListNode> list = new ArrayList<>();
        while (head != null){
            list.add(head);
            head = head.next;
        }
        if (list.size() < k || k == 1){
            return list.get(0);
        }
        int c = list.size() / k;
        for (int i = 0; i < c; i++) {
            int sta = i * k;
            int end = sta + k - 1;
            if (end + k < list.size()) {
                list.get(sta).next = list.get(end + k);
            }else if (end + 1 < list.size()){
                list.get(sta).next = list.get(end + 1);
            }else {
                list.get(sta).next = null;
            }
            for(int j = end; j > sta; j--){
                list.get(j).next = list.get(j - 1);
            }
        }
        return list.get(k - 1);
    }
}
